// 编写store
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const foodsStore = createSlice({
  name: "foods",
  initialState: {
    foodsList: [], // 商品列表
    activeIndex: 0, //菜单激活下标值
    cartList: [], // 保存购物车的数据
  },
  reducers: {
    // 更改商品列表
    setFoodsList(state, action) {
      state.foodsList = action.payload;
    },
    //更改activeIndex
    changeActiveIndex(state, action) {
      state.activeIndex = action.payload;
    },
    // 修改购物车的数据
    updateCartList: (state, action) => {
      // 如果当前的这个商品已经添加了 需要找到这个商品在其count属性上面+1
      // 如果这个商品没有添加购物车里面 需要将当前这个商品添加购物车
      const item = state.cartList.find((v) => v.id === action.payload.id);
      if (item) {
        item.count++;
      } else {
        state.cartList.push(action.payload);
      }
    },
    // count增
    increCount(state, action) {
      // 关键点：找到当前要修改谁的count id
      const item = state.cartList.find((item) => item.id === action.payload.id);
      item.count++;
    },
    // count减
    decreCount(state, action) {
      // 关键点：找到当前要修改谁的count id
      const item = state.cartList.find((item) => item.id === action.payload.id);
      if (item.count === 1) {
        return;
      }
      item.count--;
    },
    clearCart(state){
    //   alert("您确定要清空购物车吗？"); // 显示提示信息
      state.cartList = [];
    }
  },
});

// 异步获取部分
const {
  setFoodsList,
  changeActiveIndex,
  updateCartList,
  increCount,
  decreCount,
  clearCart,
} = foodsStore.actions;
const fetchFoodsList = () => {
  return async (dispatch) => {
    // 编写异步逻辑
    const res = await axios.get("http://localhost:3000/takeaway");
    // console.log(res.data);
    
    // 调用dispatch函数提交action
    dispatch(setFoodsList(res.data));
  };
};
//导出//导出
export {
  fetchFoodsList,
  changeActiveIndex,
  updateCartList,
  increCount,
  decreCount,
  clearCart,
};
const reducer = foodsStore.reducer;

export default reducer;
